<template>
  <el-drawer
    :model-value="visible"
    @update:modelValue="$emit('update:visible', $event)"
    title="我的购物车"
    direction="rtl"
    size="400px"
    class="shopping-cart-drawer"
  >
    <div v-if="cartStore.isLoading" class="loading-state">
      <el-skeleton :rows="5" animated />
    </div>

    <div v-else-if="cart.items.length === 0" class="empty-state">
      <el-empty description="购物车是空的">
        <el-button type="primary" @click="$emit('close')">继续购物</el-button>
      </el-empty>
    </div>

    <div v-else class="cart-content">
      <div class="cart-items-list">
        <div v-for="item in cart.items" :key="item.productId" class="cart-item">
          <el-image :src="item.imageUrl" class="item-image" fit="cover"/>
          <div class="item-details">
            <div class="item-name">{{ item.productName }}</div>
            <div class="item-price">¥{{ item.price.toFixed(2) }}</div>
          </div>
          <div class="item-actions">
            <el-input-number
              :model-value="item.quantity"
              @change="(val: number) => cartStore.updateItemQuantity(item.productId, val)"
              :min="1"
              size="small"
              class="quantity-input"
            />
            <el-button type="danger" :icon="Delete" circle plain size="small" @click="cartStore.removeItem(item.productId)" />
          </div>
        </div>
      </div>
      
      <div class="cart-summary">
        <div class="summary-line">
          <span>共 {{ cart.totalQuantity }} 件商品</span>
          <span>小计: <span class="subtotal-price">¥{{ cart.totalAmount.toFixed(2) }}</span></span>
        </div>
        <div class="summary-actions">
          <el-button type="danger" plain @click="cartStore.clearCart">清空购物车</el-button>
          <el-button type="primary" @click="handleCheckout" :loading="isCheckingOut" class="checkout-button">去结算</el-button>
        </div>
      </div>
    </div>
  </el-drawer>

  <!-- We need a separate dialog for cart checkout -->
  <el-dialog
    v-model="checkoutDialogVisible"
    title="订单确认"
    width="500px"
    align-center
  >
    <div v-if="cart.items.length > 0" class="order-summary">
        <!-- Address Selection -->
        <div v-if="addresses.length" class="address-section">
            <div class="address-header">
                <span>收货地址</span>
                <el-button type="primary" link @click="openAddressDialog">新增地址</el-button>
            </div>
            <el-radio-group v-model="selectedAddressId">
                <el-radio
                    v-for="addr in addresses"
                    :key="addr.id"
                    :label="addr.id"
                    class="address-radio"
                >
                {{ addr.country }} {{ addr.province }} {{ addr.city }} {{ addr.county }} {{ addr.detailAddress }} - {{ addr.receiverName }} {{ addr.receiverPhone }}
                </el-radio>
            </el-radio-group>
        </div>
        <el-empty v-else description="暂无地址，请新增地址" />
        
        <el-divider />

        <!-- Cart items summary -->
        <div class="cost-details">
            <div v-for="item in cart.items" :key="item.productId" class="cost-line">
                <span>{{ item.productName }} x {{ item.quantity }}</span>
                <span>¥{{ (item.price * item.quantity).toFixed(2) }}</span>
            </div>
        </div>

        <el-divider />

        <div class="total-amount-line">
            <span>总计</span>
            <span class="total-price-value">¥{{ cart.totalAmount.toFixed(2) }}</span>
        </div>
    </div>
    <template #footer>
        <el-button @click="checkoutDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCheckout" :loading="isCheckingOut">确认下单</el-button>
    </template>
  </el-dialog>

  <!-- Nested Dialog for adding address -->
  <el-dialog v-model="addressDialogVisible" title="新增地址" width="500px" append-to-body>
     <el-form :model="formAddress" label-width="100px" ref="addressFormRef">
        <el-form-item label="收件人"><el-input v-model="formAddress.receiverName" /></el-form-item>
        <el-form-item label="联系电话"><el-input v-model="formAddress.receiverPhone" /></el-form-item>
        <el-form-item label="国家"><el-input v-model="formAddress.country" /></el-form-item>
        <el-form-item label="省份"><el-input v-model="formAddress.province" /></el-form-item>
        <el-form-item label="城市"><el-input v-model="formAddress.city" /></el-form-item>
        <el-form-item label="地区/县"><el-input v-model="formAddress.county" /></el-form-item>
        <el-form-item label="详细地址"><el-input v-model="formAddress.detailAddress" type="textarea" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addressDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="submitAddressForm">保存</el-button>
      </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref, reactive } from 'vue';
import { useCartStore } from '../stores/cart';
import { useUserStore } from '../stores/user';
import { ElMessage, ElMessageBox } from 'element-plus';
import apiClient from '../axios/axios';
import { Delete } from '@element-plus/icons-vue';

interface Address {
  id: number;
  receiverName: string;
  receiverPhone: string;
  country: string;
  province: string;
  city: string;
  county: string;
  detailAddress: string;
}

const props = defineProps<{ visible: boolean }>();
const emit = defineEmits(['update:visible', 'close']);

const cartStore = useCartStore();
const userStore = useUserStore();
const cart = computed(() => cartStore.cart);

const drawerVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val),
});

const handleClose = () => {
  emit('close');
};

const handleClearCart = async () => {
  await ElMessageBox.confirm('确定要清空购物车吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  });
  await cartStore.clearCart();
};


// --- Checkout Logic ---
const isCheckingOut = ref(false);
const checkoutDialogVisible = ref(false);
const addresses = ref<Address[]>([]);
const selectedAddressId = ref<number | null>(null);

const handleCheckout = async () => {
  if (cart.value.items.length === 0) {
    ElMessage.info("购物车是空的，快去逛逛吧！");
    return;
  }
  isCheckingOut.value = true;
  await loadAddresses();
  isCheckingOut.value = false;
  checkoutDialogVisible.value = true;
};

const confirmCheckout = async () => {
    if (!selectedAddressId.value) {
        ElMessage.warning("请选择一个收货地址");
        return;
    }

    isCheckingOut.value = true;
    const user = userStore.user;
    if (!user) {
        ElMessage.error("用户未登录");
        isCheckingOut.value = false;
        return;
    }

    try {
        const orderPromises: Promise<any>[] = [];
        cart.value.items.forEach(item => {
            for (let i = 0; i < item.quantity; i++) {
                const orderPayload = {
                    customerId: user.id,
                    productId: item.productId,
                    addressId: selectedAddressId.value,
                    subtotalAmount: item.price,
                    shippingFee: 0, // Assuming no extra fee per item in cart checkout
                    discountAmount: 0, // Assuming no extra discount per item
                    totalAmount: item.price,
                };
                orderPromises.push(apiClient.post('/orders', orderPayload));
            }
        });

        await Promise.all(orderPromises);
        ElMessage.success("下单成功！");
        await cartStore.clearCart();
        checkoutDialogVisible.value = false;

    } catch (error) {
        console.error("结算失败:", error);
        ElMessage.error("结算过程中出现错误，请稍后再试。");
    } finally {
        isCheckingOut.value = false;
    }
};


// --- Address Management in Dialog ---
const addressDialogVisible = ref(false);
const addressFormRef = ref<any>();

const initialForm: Omit<Address, 'id'> = {
  receiverName: '', receiverPhone: '', country: '中国', province: '', city: '', county: '', detailAddress: '',
};
const formAddress = reactive({ ...initialForm });


const loadAddresses = async () => {
  const user = userStore.user;
  if (!user) return;
  try {
    const res = await apiClient.get<Address[]>(`/address/user/${user.id}`);
    addresses.value = res.data;
    if (!selectedAddressId.value && addresses.value.length) {
      selectedAddressId.value = addresses.value[0].id;
    }
  } catch (e) {
    console.error('加载地址失败', e);
  }
};

const openAddressDialog = () => {
  Object.assign(formAddress, initialForm);
  addressFormRef.value?.clearValidate();
  addressDialogVisible.value = true;
};

const submitAddressForm = async () => {
    if (!addressFormRef.value) return;
    const user = userStore.user;
    if (!user) return;
    try {
        const payload = { ...formAddress, userId: user.id };
        const res = await apiClient.post('/address', payload);
        ElMessage.success('地址已保存');
        addressDialogVisible.value = false;
        await loadAddresses();
        selectedAddressId.value = res.data.id;
    } catch (e) {
        ElMessage.error('保存地址失败');
    }
};

</script>

<style scoped>
.shopping-cart-drawer .el-drawer__header {
  margin-bottom: 20px;
}
.cart-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.cart-items-list {
  flex-grow: 1;
  overflow-y: auto;
  padding-right: 10px;
}
.cart-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  gap: 15px;
}
.item-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  flex-shrink: 0;
}
.item-details {
  flex-grow: 1;
}
.item-name {
  font-weight: 500;
  margin-bottom: 8px;
}
.item-price {
  color: #606266;
}
.item-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}
.quantity-input {
  width: 80px;
}
.cart-summary {
  padding-top: 15px;
  border-top: 1px solid #e4e7ed;
}
.summary-line {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}
.subtotal-price {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}
.summary-actions {
  display: flex;
  justify-content: space-between;
}
.empty-state, .loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
.drawer-content {
  padding: 20px;
  display: flex;
  flex-direction: column;
  height: 100%;
}
.cart-footer {
  margin-top: auto;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.total-section {
  font-size: 18px;
}
.total-amount {
  font-weight: bold;
  color: #f56c6c;
}
.checkout-button {
  padding: 12px 20px;
}

/* Styles for checkout dialog */
.order-summary { font-size: 14px; }
.address-section { margin-bottom: 16px; }
.address-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
.address-radio { display: block; margin: 8px 0; }
.cost-details { display: flex; flex-direction: column; gap: 10px; color: #606266; }
.cost-line { display: flex; justify-content: space-between; }
.total-amount-line { display: flex; justify-content: space-between; align-items: center; font-weight: bold; }
.total-price-value { font-size: 20px; color: #F56C6C; }
</style> 